package com.like.fragment;

import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.TextView;

import com.like.adapter.TwoTabPagerAdapter;
import com.like.hospitalworld.R;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

@ContentView(R.layout.fragment_two_tab)
public class TwoTabFragment extends BaseFragment {

    @ViewInject(R.id.tab_one)
    TextView mTabOne;
    @ViewInject(R.id.tab_two)
    TextView mTabTwo;
    @ViewInject(R.id.tab_pager)
    ViewPager mTabPager;

    private Fragment[] mFragments;
    private String[] mTitles;

    private TwoTabPagerAdapter mTabAdapter;
    private View[] mTabs;

    @Override
    protected void onCreateView() {
        super.onCreateView();
        initPager();
        initTab();
        mTabPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                setTabSelected(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Event({R.id.tab_one, R.id.tab_two})
    private void tabClick(View v) {
        switch (v.getId()) {
            case R.id.tab_one:
                setTabSelected(0);
                mTabPager.setCurrentItem(0);
                break;
            case R.id.tab_two:
                setTabSelected(1);
                mTabPager.setCurrentItem(1);
                break;
        }
    }

    public void setFragments(Fragment... fragments) {
        this.mFragments = fragments;
    }

    public void setTitles(String... titles) {
        this.mTitles = titles;
    }

    private void initPager() {
        mTabAdapter = new TwoTabPagerAdapter(getChildFragmentManager());
        mTabAdapter.setFragments(mFragments);
        mTabPager.setAdapter(mTabAdapter);
    }

    private void initTab() {
        mTabOne.setText(mTitles[0]);
        mTabTwo.setText(mTitles[1]);
        mTabs = new View[]{mTabOne, mTabTwo};
        setTabSelected(0);
    }

    private void setTabSelected(int position) {
        for (View view : mTabs)
            view.setSelected(false);
        View v = mTabs[position];
        v.setSelected(true);
    }
}
